/*
 * @Author: 肖芬芳 10547202+xiao-fenfang@user.noreply.gitee.com
 * @Date: 2022-06-17 09:05:49
 * @LastEditors: 肖芬芳 1911683843@qq.com
 * @LastEditTime: 2022-12-13 15:43:08
 * @FilePath: \kindstar-youyi-webc:\Users\Administrator\Desktop\vite-project\src\store\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'
import { getItem, removeItem, setItem } from '@/util/base/storage'
import { TOKEN, USER } from '@/util/base/constants'
import { UserInfo } from '@/views/admin/login/vo/loginVo'

// 为 store state 声明类型
// export interface State {
//   count: number,
//   isCollapse:boolean
// }

const state = {
  count: 0,
  isCollapse: false,
  user: getItem<UserInfo>(USER),
  token: getItem<string>(TOKEN)
}

// typeof推导数据类型
export type State=typeof state

// 定义 injection key
// 希望 useStore 返回类型化的 store
export const key: InjectionKey<Store<State>> = Symbol('store')

// 创建一个新的 store 实例
export const store = createStore<State>({
  state,
  mutations: {
    increment (state) {
      state.count++
    },
    changeIsCollapse (state) {
      // 取反
      state.isCollapse = !state.isCollapse
    },
    setUser (state, payload) {
      state.user = payload
      setItem(USER, state.user, 60)
    },
    removeUser (state) {
      state.user = null
      removeItem(USER)
    },
    setToken (state, payload) {
      state.token = 'Bearer ' + payload
      setItem(TOKEN, state.token, 60)
    },
    removeToken (state) {
      state.token = null
      removeItem(TOKEN)
    }
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore () {
  return baseUseStore(key)
}
